import React from 'react';
import {
    Image,
    Modal,
    StatusBar,
    Text,
    TouchableOpacity,
    View,
    StyleSheet,
    DeviceEventEmitter,
    TextInput, Keyboard,
} from 'react-native';
import Constants from '../utils/Constants';
import screen from '../utils/screen';
import RequestUtil from '../utils/RequestUtil';
import DialogTip from '../widgets/modal/DialogTip';
import Api from '../utils/Api';
import {
    AppInfo,
    cutZero,
    filterErrorMsg,
    FontFamily,
    getffly,
    numMulti,
    numSub,
    setTextThousand,
} from '../utils/common';
import {AlertModal, AppModal} from '../widgets/modal';
import Images from '../images/Images';
import {LGBtn,GrayBtn} from '../widgets/buttons';
import AppEvent from '../utils/AppEvent';


export default  class InvestDialog extends React.Component {

    constructor(props) {
        super(props);

    }

    state={
        modalVisible:false,
        data:null,
        moneyInput:''
    }


    componentDidMount = () => {

    }


    invest= ()=>{

        let param = {
            id:this.state.data.id,
            amount:this.state.moneyInput
        }

        this.tipDialog.showLoading();

        RequestUtil.post(Api.invest,param,true).then(res=>{
            console.log('invest',res)
            const data =res.data
            this.tipDialog.hideDialog()
            this.tipDialog.showSuccess(Constants.account.successfully_invested)
            this.hideDialog()
            this.onConfirm && this.onConfirm()

        },error=>{
            this.tipDialog.hideDialog()
            if(error.code === -4){
                this.alertDialog.alert(Constants.common.failed,error.msg,[
                    {
                        title:Constants.common.cancel,
                        onPress:()=>{
                            this.hideDialog()
                        }
                    },
                    {
                        title:Constants.common.upgrade,
                        onPress:()=>{
                            this.hideDialog()
                            //升级vip
                            this.props.navigation.navigate('Vip')
                            DeviceEventEmitter.emit(AppEvent.update_vip)
                    }}
                ])
            }else if(error.code === -11){
                this.onConfirm()

            }else{
                this.alertDialog.alert(Constants.common.failed,error.msg,[{
                    title:Constants.common.OK,
                    onPress:()=>{
                        this.hideDialog()
                    }
                }])
            }
        })
    }

    onInvestClick = ()=>{
        Keyboard.dismiss()
        const {moneyInput,data} = this.state
        if(Number(moneyInput) < Number(data.starting_amount)){
            const content = Constants.account.interest_amount_1 + ' ' + Constants.appsymbol + ' ' + setTextThousand(cutZero(data.starting_amount)) + Constants.account.interest_amount_2
            this.alertDialog.alert(Constants.common.failed,content,[
                {
                    title:Constants.common.OK,
                    onPress:()=>{
                        this.alertDialog.hideDialog()
                    }
                }
            ])
        }else if(Number(moneyInput) > Number(data.balance) ){
            const content = Constants.account.current_balance_is_not_enough + Constants.appsymbol + ' ' + setTextThousand(numSub(moneyInput,data.balance)) + '.'
            this.alertDialog.alert(Constants.common.failed,content,[
                {
                    title:Constants.common.cancel,
                    onPress:()=>{
                        this.alertDialog.hideDialog()
                    }
                },{
                    title:Constants.account.recharge,
                    onPress:()=>{
                        this.alertDialog.hideDialog()
                        this.hideDialog()
                        this.props.navigation.navigate('Recharge')
                    }
                }
            ])
        }else{
            this.invest()
        }
    }


    hideDialog = () => {

        this.setState({ modalVisible: false });
    }

    show = (data,onConfirm)=>{
        this.onConfirm = onConfirm
        this.setState({
            data,
            modalVisible:true
        })
    }


    renderRowItem(leftTitle,rightTitle){
        return(
            <View style={{flexDirection: 'row',justifyContent:'space-between'}}>
                <Text style={{fontSize: 13,color:'#000'}}>{leftTitle}</Text>
                <Text style={{fontSize: 13,color:'#000'}}>{rightTitle}</Text>
            </View>
        )
    }

    renderContent(){

        const {data} = this.state
        if(!data) return null
        let isMoneyEnough = true
        if(Number(data.balance ) < Number(data.starting_amount) ){
            isMoneyEnough = false
            console.log('余额不足')
        }
        return (
            <View style={styles.innerContainer}>

                <View style={styles.contentBg}>
                    <Text style={{fontSize:13,color:'#000'}}>{Constants.account.investment_amount}</Text>

                    <View style={styles.codeInputWrap}>
                        <TextInput
                            keyboardType='numeric'
                            allowFontScaling={false}
                            placeholderTextColor={'rgba(255, 255, 255, 0.35)'}
                            placeholder={Constants.login.verification}
                            style={ styles.codeInput}
                            value={this.state.moneyInput}
                            onChangeText={(text) => {
                                this.setState({
                                    moneyInput:text
                                })

                            }}
                        />
                        {
                            isMoneyEnough ? (
                                <TouchableOpacity
                                    style={styles.sendBtn}
                                    onPress={()=>{
                                        this.setState({
                                            moneyInput:data.balance
                                        })
                                    }}
                                >
                                    <Text style={{color:'#377C74',fontSize:20,}}>{'All in'}</Text>
                                </TouchableOpacity>
                            ):(
                                <TouchableOpacity
                                    style={styles.sendBtn}
                                    onPress={()=>{
                                        this.hideDialog()
                                        this.props.navigation.navigate('Recharge')
                                    }}
                                >
                                    <Text style={{color:'#377C74',fontSize:14,}}>{Constants.account.recharge}</Text>
                                </TouchableOpacity>
                            )
                        }



                    </View>
                    {
                        isMoneyEnough ? (
                            <Text style={{fontSize:15,color:'#FF7012',marginBottom:screen.PIXEL_20}}>{`${Constants.vip.current_balance} ${Constants.appsymbol} ${setTextThousand(cutZero(data.balance))}`}</Text>
                        ):(
                            <Text style={{fontSize:15,color:'#FF7012',marginBottom:screen.PIXEL_20}}>{Constants.account.current_balance_is_not_enough}</Text>
                        )
                    }



                    {this.renderRowItem(Constants.account.starting_amount,`${Constants.appsymbol} ${setTextThousand(cutZero(data.starting_amount))}`)}
                    {this.renderRowItem(Constants.account.cycle,`${data.cycle}${Constants.account.days}`)}
                    {this.renderRowItem(Constants.account.interest,numMulti(data.interest_rate,100)+'%')}

                </View>


                {
                    isMoneyEnough ? (
                        <LGBtn
                            title={Constants.account.invest_now}
                            style={{width:'100%',height:screen.PIXEL_80,marginTop:screen.PIXEL_40}}
                            onPress={()=>this.onInvestClick()}
                        />
                    ):(
                        <GrayBtn
                            title={Constants.account.invest_now}
                            style={{width:'100%',height:screen.PIXEL_80,marginTop:screen.PIXEL_40}}
                        />
                    )
                }


                <Text style={{fontSize: 13,color:'#999',marginTop:screen.PIXEL_10,marginHorizontal:screen.PIXEL_60}}>{`${Constants.account.early_redemption_1}${numMulti(data.redemption_fee,100)}${Constants.account.early_redemption_2}`}</Text>



            </View>

        )
    }



    render() {




        return (
            <Modal
                animationType={'none'}
                transparent={true}
                visible={this.state.modalVisible}
                onRequestClose={() => { this._setModalVisible(false) }}
                onShow={this.startShow}
            >
                <StatusBar barStyle='light-content' translucent={true} backgroundColor="rgba(16, 17, 22,0.75)" animated={false} />
                <TouchableOpacity
                    activeOpacity={1.0}
                    onPress={() => {

                    }}
                    style={styles.bottomcontainer}>

                    <View style={styles.container}>

                        {this.renderContent()}

                        <TouchableOpacity
                            style={{marginTop:screen.PIXEL_60}}
                            onPress={()=>{
                                this._setModalVisible(false)
                            }}
                        >
                            <Image source={Images.close} style={styles.close}/>
                        </TouchableOpacity>

                    </View>
                    <DialogTip ref={ref=>{this.tipDialog = ref}} />
                    <AlertModal ref={ref=>{this.alertDialog = ref}}/>
                </TouchableOpacity>
            </Modal>
        );
    }


    _setModalVisible = (visible) => {
        this.setState({ modalVisible: visible });
    }

    startShow = () => {

    }
}



const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    innerContainer: {
        width: screen.width - screen.PIXEL_100,
        padding:screen.PIXEL_40,
        backgroundColor: '#FFFFFF',
        justifyContent:'center',
        alignItems: 'center',
        borderRadius: screen.PIXEL_50
    },

    close:{
        width:screen.PIXEL_70,
        height:screen.PIXEL_70
    },
    codeInputWrap:{
        marginTop:screen.PIXEL_40,
        width:'100%',
        height:screen.PIXEL_80,
        flexDirection:'row',
    },
    bottomcontainer: {
        zIndex: 2,
        flex: 1,
        alignItems: 'center',
        backgroundColor: 'rgba(16, 17, 22,0.75)',
        justifyContent: 'flex-end',
    },
    contentBg:{
        marginTop: screen.PIXEL_40,width:'100%'

    },codeInput:{
        fontFamily: getffly(FontFamily.bold),
        flex:1,
        fontSize:20,
        padding:0,
        color:'#000',
        marginRight:6,
        borderBottomWidth:1,
        borderBottomColor:'rgba(32,32,32,0.3)'
    }, sendBtn:{
        width:screen.PIXEL_160,height:screen.PIXEL_80,borderWidth:2,
        borderColor:'#377C74',borderRadius: screen.PIXEL_40,
        justifyContent: 'center',
        alignItems:'center'
    }

});



